#!/bin/bash

SCRIPT=$(readlink -f "$0")
INSTALLPATH=$(dirname "${SCRIPT}")
TOPDIR=$(dirname "${INSTALLPATH}")
DATASDIR=${TOPDIR}/datas/
PROJECT_NAME=$(basename "$PWD")

manage_py=${INSTALLPATH}/manage.py

if [[ ! -d "${DATASDIR}" ]]; then
    mkdir -p ${DATASDIR}
fi
# 创建日志文件夹
if [[ ! -d "${DATASDIR}/logs" ]]; then
    mkdir ${DATASDIR}/logs
fi
if [[ ! -d "${DATASDIR}/db" ]]; then
    mkdir ${DATASDIR}/db
fi

python3 ${manage_py} makemigrations 1>> ${DATASDIR}/logs/${PROJECT_NAME}_service.log
python3 ${manage_py} migrate 1>> ${DATASDIR}/logs/${PROJECT_NAME}_service.log
python3 ${manage_py} loaddata site_options 1>> ${DATASDIR}/logs/${PROJECT_NAME}_service.log

echo "
from django.contrib.auth import get_user_model
User = get_user_model()
new_user = User.objects.create_superuser('${USER,,}@${HOSTNAME,,}.com', 'admin123', nickname='管理员', coin=9999, renzheng='社区超级管理员')
" | python3 manage.py shell
if [[ "$?" == 0 ]]; then
    printf "\033[1;32m初始化管理员账号，请注意妥善保管\n邮箱：${USER,,}@${HOSTNAME,,}.com\n密码：admin123\033[m\n"
else
    echo "初始化失败，请检查日志或控制台输出"
fi
